//
//  FaceIDExampleVC.m
//  Peso Guide
//
//  Created by macbook on 2025/6/13.
//

#import "FaceIDExampleVC.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "PreviewViewController.h"

@interface FaceIDExampleVC ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) NSString *inconvenient;//图片来源:1拍照 2:相册选择

@end

@implementation FaceIDExampleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSString *startTime = [DataPointManager getCurrentTimestamp];
    [[NSUserDefaults standardUserDefaults] setObject:startTime forKey:@"upLogType-4-startTime"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [[LocationManager sharedManager] getCurrentLocationWithSuccess:^(CLLocationCoordinate2D coordinate) {
            DLog(@"get location success：log=%f, lat=%f", coordinate.longitude, coordinate.latitude);
            
            NSString *lng = [NSString stringWithFormat:@"%f",coordinate.longitude];
            NSString *lat = [NSString stringWithFormat:@"%f",coordinate.latitude];

            [[NSUserDefaults standardUserDefaults] setObject:lng forKey:@"upLogType-4-lng"];
            [[NSUserDefaults standardUserDefaults] setObject:lat forKey:@"upLogType-4-lat"];
            [[NSUserDefaults standardUserDefaults] synchronize];

            // 使用获取到的经纬度做其他操作...
            
        } failure:^(NSError *error) {
            // 处理错误情况...
        }];
    
    self.navView.backgroundColor = ColorHex(@"#1A7A35");
    self.titleLabel.text = [Lang set:@"Identity information"];
    self.backColor = ColorHex(@"#F3F4F8");
    
    CAGradientLayer *layer = [CAGradientLayer new];
    layer.colors = @[(__bridge id)ColorHex(@"#FFBD31").CGColor, (__bridge id)ColorHex(@"#FFFFFF").CGColor];
    layer.startPoint = CGPointMake(0.0, 0.0);
    layer.endPoint = CGPointMake(0.0, 1);
    layer.frame = CGRectMake(0, 0, KScreenWidth, KScreenWidth*0.736);
    [self.view.layer addSublayer:layer];
    
    UILabel *topLabel = [PesoKit createLabelWithFrame:CGRectMake(27, kStarBarHeight, KScreenWidth-54, 66) backGroundColor:[UIColor clearColor] text:[Lang set:@"When performing recognition, follow theinstructions to complete the action"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleRegular, 12)];
    topLabel.numberOfLines = 0;
    [self.view addSubview:topLabel];
    
    _whiteView = [PesoKit createViewWithFrame:CGRectMake(0, kStarBarHeight+KScreenWidth*0.736*0.24, KScreenWidth, KScreenHeight) backGroundColor:ColorHex(@"#FFFFFF")];
    _whiteView.clipsToBounds = YES;
    _whiteView.layer.cornerRadius = 15.0f;
    [self.view addSubview:_whiteView];
    
    UILabel *trueLabel = [PesoKit createLabelWithFrame:CGRectMake(24, 20, KScreenWidth-40, 22) backGroundColor:ColorHex(@"#FFFFFF") text:[Lang set:@"Demonstration"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleMedium, 16)];
    [_whiteView addSubview:trueLabel];
    
    UIImageView *trueImg = [PesoKit createImageViewWithFrame:CGRectMake((KScreenWidth-220)/2.0, 54, 220, 136) imageNamed:@"ic_identity_face_id"];
    [_whiteView addSubview:trueImg];
    
    UILabel *faildLabel = [PesoKit createLabelWithFrame:CGRectMake(24, 210, KScreenWidth-40, 22) backGroundColor:ColorHex(@"#FFFFFF") text:[Lang set:@"Wrong demonstration"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleMedium, 16)];
    [_whiteView addSubview:faildLabel];
    
    NSArray *faildImgArr = @[@"ic_identity_face_id_faild4",@"ic_identity_face_id_faild5",@"ic_identity_face_id_faild6"];
    
    for (int i = 0; i < 3; i++) {
        UIImageView *faildImg = [PesoKit createImageViewWithFrame:CGRectMake(24+(KScreenWidth-48-12)/3.0*i+6*i, 248, (KScreenWidth-48-12)/3.0, ((KScreenWidth-48-12)/3.0)*0.62) imageNamed:@"ic_identity_id_card"];
        faildImg.image = [UIImage imageNamed:[faildImgArr safeObjectAtIndex:i]];
        [_whiteView addSubview:faildImg];
        
        UIImageView *faildIcon = [[UIImageView alloc] init];
        faildIcon.image = [UIImage imageNamed:@"ic_identity_faild"];
        faildIcon.center = faildImg.center;
        faildIcon.bounds = CGRectMake(0, 0, 20, 20);
        faildIcon.top = faildImg.bottom+8;
        [_whiteView addSubview:faildIcon];
    }
    
    _nextButton = [PesoKit createButtonWithFrame:CGRectMake((KScreenWidth-214)/2.0, KScreenHeight-kSafeBottomHeight-30-44, 214, 44) backGroundColor:ColorHex(@"#FE7133") title:[Lang set:@"Next"] titleColor:ColorHex(@"#FFFFFF") font:FONT(FontWeightStyleMedium, 18)];
    _nextButton.clipsToBounds = YES;
    _nextButton.layer.cornerRadius = 22.0f;
    [_nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextButton];
    
    [self.view addSubview:self.navView];
}

- (void)nextButtonClick {
    [self showActionSheetForCameraType:UIImagePickerControllerCameraDeviceFront];
}

- (void)showActionSheetForCameraType:(UIImagePickerControllerCameraDevice)cameraType {
//    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil
//                                                                         message:[Lang set:@"Please choose"]
//                                                                preferredStyle:UIAlertControllerStyleActionSheet];
//    // 相机选项
//    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:[Lang set:@"Camera"]
//                                                          style:UIAlertActionStyleDefault
//                                                        handler:^(UIAlertAction * _Nonnull action) {
//        [self checkCameraPermission:^(BOOL granted) {
//            if (granted) {
//                self.inconvenient = @"1";
//                [self openCameraWithDeviceType:cameraType];
//            } else {
//                [self showPermissionAlert:[Lang set:@"Camera"]];
//            }
//        }];
//    }];
    
    // 相册选项
//    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:[Lang set:@"Album"]
//                                                         style:UIAlertActionStyleDefault
//                                                       handler:^(UIAlertAction * _Nonnull action) {
//        [self checkPhotoLibraryPermission:^(BOOL granted) {
//            if (granted) {
//                self.inconvenient = @"2";
//                [self openPhotoLibrary];
//            } else {
//                [self showPermissionAlert:[Lang set:@"Album"]];
//            }
//        }];
//    }];
    
//    // 取消选项
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[Lang set:@"Cancel"]
//                                                          style:UIAlertActionStyleCancel
//                                                        handler:nil];
//    
//    [actionSheet addAction:cameraAction];
////    [actionSheet addAction:albumAction];
//    [actionSheet addAction:cancelAction];
//    
//    [self presentViewController:actionSheet animated:YES completion:nil];
    
    [self checkCameraPermission:^(BOOL granted) {
        if (granted) {
            self.inconvenient = @"1";
            [self openCameraWithDeviceType:cameraType];
        } else {
            [self showPermissionAlert:[Lang set:@"Camera"]];
        }
    }];
}


// 检查相机权限
- (void)checkCameraPermission:(void(^)(BOOL granted))completion {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusAuthorized) {
        completion(YES);
    } else if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(granted);
            });
        }];
    } else {
        completion(NO);
    }
}

// 检查相册权限
- (void)checkPhotoLibraryPermission:(void(^)(BOOL granted))completion {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) {
        completion(YES);
    } else if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(status == PHAuthorizationStatusAuthorized);
            });
        }];
    } else {
        completion(NO);
    }
}


// 打开指定摄像头（禁用切换功能）
- (void)openCameraWithDeviceType:(UIImagePickerControllerCameraDevice)deviceType {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:[Lang set:@"Error"]
                                                                           message:[Lang set:@"The device does not support cameras"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:[Lang set:@"Confirm"] style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
        
        return;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.mediaTypes = @[(NSString *)kUTTypeImage];
    picker.allowsEditing = NO;
    picker.cameraDevice = deviceType;
    
    // 创建自定义相机覆盖视图
    UIView *cameraOverlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0, picker.view.frame.size.width, picker.view.frame.size.height)];
    cameraOverlay.backgroundColor = [UIColor clearColor];
    
    // 添加自定义顶部栏
    UIView *topBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cameraOverlay.frame.size.width, kStarBarHeight)];
    topBar.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];
    
    // 添加关闭按钮
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    closeButton.frame = CGRectMake(10, kStatusBarHeight, 60, 44);
    [closeButton setTitle:[Lang set:@"Close"] forState:UIControlStateNormal];
    [closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(dismissCamera) forControlEvents:UIControlEventTouchUpInside];
    [topBar addSubview:closeButton];
    
    // 添加拍照按钮
    UIButton *captureButton = [UIButton buttonWithType:UIButtonTypeSystem];
    captureButton.frame = CGRectMake((cameraOverlay.frame.size.width - 70)/2, cameraOverlay.frame.size.height - 100, 70, 70);
    captureButton.backgroundColor = [UIColor whiteColor];
    captureButton.layer.cornerRadius = 35;
    captureButton.layer.borderWidth = 5;
    captureButton.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1.0].CGColor;
    [captureButton addTarget:picker action:@selector(takePicture) forControlEvents:UIControlEventTouchUpInside];
    
    [cameraOverlay addSubview:topBar];
    [cameraOverlay addSubview:captureButton];
    
    picker.showsCameraControls = NO;
    picker.cameraOverlayView = cameraOverlay;
    
    [self presentViewController:picker animated:YES completion:nil];
}

// 打开相册
- (void)openPhotoLibrary {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.mediaTypes = @[(NSString *)kUTTypeImage];
    picker.allowsEditing = NO;
    
    // iOS 11+ 设置选择单张照片
    if (@available(iOS 11.0, *)) {
        picker.videoExportPreset = AVAssetExportPresetPassthrough;
    }
    picker.modalPresentationStyle = UIModalPresentationFullScreen;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
        
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    if (!originalImage) return;
    
    // 显示预览页面
    PreviewViewController *previewVC = [[PreviewViewController alloc] init];
    previewVC.photo = originalImage;
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        previewVC.sourceType = PhotoSourceTypeCamera;
        previewVC.useFrontCamera = (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront);
    } else {
        previewVC.sourceType = PhotoSourceTypeAlbum;
    }
    
    // 设置重拍回调
    __weak typeof(self) weakSelf = self;
    previewVC.onRetake = ^{
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            [weakSelf openCameraWithDeviceType:picker.cameraDevice];
        } else {
            [weakSelf openPhotoLibrary];
        }
    };
    
    // 设置确认回调
    previewVC.onConfirm = ^(UIImage *compressedImage) {
        [weakSelf handleCompressedImage:compressedImage];
    };
    
    previewVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:previewVC animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleCompressedImage:(UIImage *)compressedImage {
    
    [SVProgressHUD dismiss];
    // 显示图片信息
    
    // 在后台线程执行压缩操作
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *compressedData = [self compressImage:compressedImage toMaxSize:1000 * 1024];
            dispatch_async(dispatch_get_main_queue(), ^{
                CGFloat sizeKB = compressedData.length / 1024.0;
                DLog(@"The picture compression is completed，size: %.2fKB", sizeKB);
                
                [self.idCardFaceIDVC upLoadFaceCard:@{@"img":compressedImage,@"imgData":compressedData,@"inconvenient":self.inconvenient}];
                [self.navigationController popToViewController:self.idCardFaceIDVC animated:YES];
            });
        });
}

// 核心压缩算法

- (NSData *)compressImage:(UIImage *)image toMaxSize:(NSUInteger)maxSize {
    CGFloat compressionQuality = 0.85f; // 初始压缩质量
    CGFloat maxDimension = 2048;        // 最大边长限制
    
    // 1. 尺寸压缩
    UIImage *resizedImage = [self resizeImage:image maxDimension:maxDimension];
    
    // 2. 质量压缩（二分法优化）
    NSData *compressedData = UIImageJPEGRepresentation(resizedImage, compressionQuality);
    
    // 质量压缩循环（最多8次）
    int count = 0;
    while (compressedData.length > maxSize && compressionQuality > 0.1f && count++ < 8) {
        compressionQuality -= 0.1f;
        compressedData = UIImageJPEGRepresentation(resizedImage, compressionQuality);
    }
    
    // 3. 如果仍然超限，进行降分辨率处理
    if (compressedData.length > maxSize) {
        resizedImage = [self resizeImage:resizedImage maxDimension:maxDimension * 0.7];
        compressedData = UIImageJPEGRepresentation(resizedImage, 0.5); // 使用中等质量
    }
    
    return compressedData.length <= maxSize ? compressedData : nil;
}

- (UIImage *)resizeImage:(UIImage *)image maxDimension:(CGFloat)maxDimension {
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    // 计算缩放比例
    CGFloat scale = 1.0f;
    if (width > maxDimension || height > maxDimension) {
        scale = MIN(maxDimension/width, maxDimension/height);
    }
    
    if (scale >= 1.0) return image; // 无需缩放
    
    // 创建新的尺寸
    CGSize newSize = CGSizeMake(width * scale, height * scale);
    UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.8); // 0.8的缩放因子节省内存
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage;
}

// 辅助方法

// 显示权限提示
- (void)showPermissionAlert:(NSString *)permissionName {
    NSString *message = [NSString stringWithFormat:[Lang set:@"Please allow the application to access %@ to continue. You can modify the permissions in Settings - Privacy -%@"], permissionName, permissionName];
        
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[Lang set:@"The permission was rejected"]
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[Lang set:@"Cancel"]
                                                              style:UIAlertActionStyleCancel
                                                            handler:nil];
        
    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:[Lang set:@"Confirm"]
                                                                style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * _Nonnull action) {
            [self openAppSettings];
        }];
        
        [alert addAction:cancelAction];
        [alert addAction:settingsAction];
        
        [self presentViewController:alert animated:YES completion:nil];
}

- (void)openAppSettings {
    NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    
    if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:settingsURL];
        }
    }
}

// 关闭相机
- (void)dismissCamera {
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
